package org.aphelie.chronicle.ui.forms;

import org.aphelie.chronicle.ArcElement;
import org.aphelie.chronicle.ArcScore;
import org.aphelie.chronicle.ChroniclePackage;
import org.aphelie.chronicle.ui.validators.ControlValidationUtility;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;

public class ScoreEntry extends ArcFormEntry {
	
	private static final EAttribute FEATURE = ChroniclePackage.eINSTANCE.getArcScore_Value();
	
	private ArcScore score;
	
	public ScoreEntry(Composite parent, FormToolkit toolkit, ArcFormSection section, ArcScore score) {
		super(parent, toolkit, section, score);
		this.score = score;
		refresh();
	}
	
	protected boolean validateEntry() {
		String text = getText().getText();
		if (ControlValidationUtility.validateRequiredField(text, validator, IMessageProvider.ERROR) == false) {
			return false;
		}
		return ControlValidationUtility.validateNumericField(text, validator, IMessageProvider.ERROR) ;
	}

	@Override
	protected void setAttributeValue(ArcElement element, String value) {
		try {
			int intValue = 0;
			if (value != null && value.length() > 0) {
				intValue = Integer.parseInt(value);
			}
			if (element.eContainer() == null) {
				((ArcTupleSection)getSection()).getTuple().getScores().add(score);
			}
			
			getEditingDomain().getCommandStack().execute(SetCommand.create(getEditingDomain(), element, FEATURE, intValue));
			getSection().markStale();
		} catch (Exception e) {
			e.printStackTrace(); // Latter ignore
		}
	}
	
	public void refresh() {
		setValue(String.valueOf(score.getValue()), true);
	}

}
